﻿using System.Collections;
using UnityEngine;

[RequireComponent(typeof(LineRenderer))]
public class Laser : MonoBehaviour
{
    private EventSystem eventSystem;
    private LineRenderer ray;

    [Header("周期(可选)")]
    [SerializeField]
    private float[] cycle;
    private float offsetDistance;
    //射线的方向（相对方向，总是相对于激光器向前）
    private Vector3 rayDirection = new Vector3(0, 1f, 0);
    private bool initialActivity;

    [SerializeField]
    private bool _Active;
    public bool Active
    {
        get => _Active;
        set
        {
            ray.enabled = value;
            _Active = value;
        }
    }

    /// <summary>
    /// 射线最长距离
    /// </summary>
    public float maxDistance = 10f;
    private LayerMask targetLayer;
    private LayerMask playerLayer;

    private void Awake()
    {
        eventSystem = Service.Get<EventSystem>();
        offsetDistance = 0.3f;
        ray = GetComponent<LineRenderer>();
        ray.SetPositions(new Vector3[2]);
        targetLayer =  Service.Get<GameManager>().groundLayer;
        playerLayer =  Service.Get<GameManager>().playerLayer;
        initialActivity = _Active;
        ray.enabled = _Active;
        StartCoroutine(LifeCycle());
    }

    private void OnEnable()
    {
        eventSystem.PlayerDie += MyReset;
    }
    private void OnDisable()
    {
        eventSystem.PlayerDie -= MyReset;
    }

    public void MyReset()
    {
        Active = initialActivity;
        StopAllCoroutines();
        StartCoroutine(LifeCycle());
    }

    private void OnTriggerStay2D(Collider2D collision)
    {
        Character player = collision.GetComponent<Character>();
        if (player != null && Active)
        {
            player.Die();
        }
    }

    private void FixedUpdate()
    {
        Launch();
    }

    private void Launch()
    {
        Vector2 direction = (-transform.eulerAngles.z).ToDirection();
        Vector3 relativeOffset = offsetDistance * rayDirection;
        float distance = PhysicsTool.RaycastRanging(transform.position + offsetDistance * direction.AddZ(), direction, maxDistance, targetLayer);

        ray.SetPosition(0, relativeOffset);
        ray.SetPosition(1, relativeOffset + distance * rayDirection);

        if(Active)
        {
            float distance_player = PhysicsTool.RaycastRanging(transform.position + offsetDistance * direction.AddZ(), direction, maxDistance, playerLayer);
            if (distance_player < distance)
                Character.Instance.Die();
        }
    }


    private IEnumerator LifeCycle()
    {
        if (cycle == null || cycle.Length == 0)
            yield break;
        for (; ; )
        {
            for (int i = 0; i < cycle.Length; i++)
            {
                yield return new WaitForSeconds(cycle[i]);
                Active = !Active;
            }
        }
    }

}